<template>
    <div class="audio-player">
        <audio ref="audioRef" @timeupdate="updateProgress" @ended="handleEnded" @error="handleAudioError"></audio>
        <div class="audio-controls">
            <button class="play-btn" @click="togglePlay" :disabled="!audioData">
                {{ isPlaying ? '暂停' : '播放' }}
            </button>
            <div class="progress-container">
                <input
                        type="range"
                        class="progress-bar"
                        :value="progress"
                        @input="seek"
                        :disabled="!audioData"
                />
                <span class="time-display">{{ formattedTime }} / {{ formattedDuration }}</span>
            </div>
            <button class="download-btn" @click="downloadAudio" :disabled="!audioData">
                下载
            </button>
        </div>
    </div>
</template>

<script setup>
import {ref, computed, watch} from 'vue';
import * as audioService from '../services/audioService';

const props = defineProps({
    audioData: {
        type: Object,
        default: null
    }
});

const audioRef = ref(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const progress = ref(0);

// 格式化时间显示
const formattedTime = computed(() => {
    return formatTime(currentTime.value);
});

const formattedDuration = computed(() => {
    return formatTime(duration.value);
});

function formatTime(seconds) {
    if (isNaN(seconds) || seconds === 0) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 监听音频数据变化
watch(
    () => props.audioData,
    (newAudioData) => {
        if (newAudioData && newAudioData.audioUrl) {
            loadAudio(newAudioData.audioUrl);
        } else {
            resetPlayer();
        }
    },
    {immediate: true}
);

function loadAudio(audioUrl) {
    const audio = audioRef.value;
    if (audio) {
        audio.src = audioUrl;
        audio.load();
        audio.addEventListener('loadedmetadata', () => {
            duration.value = audio.duration || 0;
        });
    }
}

function togglePlay() {
    const audio = audioRef.value;
    if (!audio || !props.audioData) return;

    if (isPlaying.value) {
        audio.pause();
    } else {
        audio.play().catch(error => {
            console.error('播放音频失败:', error);
            handleAudioError(error);
        });
    }
    isPlaying.value = !isPlaying.value;
}

function updateProgress() {
    const audio = audioRef.value;
    if (audio && duration.value > 0) {
        currentTime.value = audio.currentTime;
        progress.value = (currentTime.value / duration.value) * 100;
    }
}

function seek(event) {
    const audio = audioRef.value;
    if (!audio || !props.audioData) return;

    const newTime = (event.target.value / 100) * duration.value;
    audio.currentTime = newTime;
    currentTime.value = newTime;
}

function handleEnded() {
    isPlaying.value = false;
    currentTime.value = 0;
    progress.value = 0;
}

function handleAudioError(error) {
    console.error('音频播放错误:', error);
    isPlaying.value = false;
    // 可以在这里添加错误提示给用户
}

function downloadAudio() {
    if (!props.audioData || !props.audioData.audioUrl) return;

    const link = document.createElement('a');
    link.href = props.audioData.audioUrl;
    link.download = `audio_${Date.now()}.mp3`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function resetPlayer() {
    const audio = audioRef.value;
    if (audio) {
        audio.pause();
        audio.src = '';
    }
    isPlaying.value = false;
    currentTime.value = 0;
    duration.value = 0;
    progress.value = 0;
}

// 暴露方法给父组件
defineExpose({
    togglePlay,
    resetPlayer
});
</script>

<style scoped>
.audio-player {
    margin: 10px 0;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.audio-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.play-btn,
.download-btn {
    padding: 6px 12px;
    background-color: #4a5568;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.play-btn:hover:not(:disabled),
.download-btn:hover:not(:disabled) {
    background-color: #2d3748;
}

.play-btn:disabled,
.download-btn:disabled {
    background-color: #a0aec0;
    cursor: not-allowed;
}

.progress-container {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;
}

.progress-bar {
    flex: 1;
    height: 6px;
    -webkit-appearance: none;
    appearance: none;
    background: #cbd5e0;
    border-radius: 3px;
    outline: none;
}

.progress-bar::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 16px;
    height: 16px;
    background: #4a5568;
    border-radius: 50%;
    cursor: pointer;
}

.progress-bar::-moz-range-thumb {
    width: 16px;
    height: 16px;
    background: #4a5568;
    border-radius: 50%;
    cursor: pointer;
    border: none;
}

.progress-bar:disabled {
    background: #e2e8f0;
    cursor: not-allowed;
}

.time-display {
    font-size: 12px;
    color: #4a5568;
    min-width: 70px;
    text-align: right;
}
</style>